package cn.git.controller;

import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @description: 文件路径测试
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2023-08-08
 */
@RestController
@RequestMapping("/path")
public class PathTestController {

    /**
     * 生成一个文件到resource目录下
     *
     * @return
     */
    @GetMapping("/makeFile")
    public String makeFile() {
        // 在服务根目录创建一个文件
        String bathPath = System.getProperty("user.dir").concat(StrUtil.SLASH).concat("test.txt");
        File file = new File(bathPath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("123");
            fileWriter.flush();
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    /**
     * 读取文件内容v
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/getFile")
    public String getFile() throws IOException {
        String bathPath = System.getProperty("user.dir").concat(StrUtil.SLASH).concat("test.txt");
        File file = new File(bathPath);
        // 读取txt内容信息
        FileReader fileReader = new FileReader(file);
        char[] chars = new char[1024];
        int len = fileReader.read(chars);
        fileReader.close();
        return new String(chars, 0, len);
    }

    /**
     * 删除文件
     *
     * @return
     */
    @GetMapping("/dropFile")
    public String dropFile() {
        String bathPath = System.getProperty("user.dir").concat(StrUtil.SLASH).concat("test.txt");
        File file = new File(bathPath);
        if (file.exists()) {
            file.delete();
        }
        return "删除成功";
    }

    /**
     * 读取resource目录下的文件
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/getResourceFile")
    public String getResourceFile() throws IOException {
        // 通过classLoader获取inputStream
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("name.txt");
        StringBuilder content = new StringBuilder();
        try {
            assert inputStream != null;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line).append("\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }

}
